/*
 * @Author: your name
 * @Date: 2021-05-26 16:07:07
 * @LastEditTime: 2021-05-26 17:35:11
 * @LastEditors: Please set LastEditors
 * @Description: 接口调用凭证access_token的缓存与更新
 * @FilePath: \bazai_music_api\utils\getAccessToken.js
 */
const fs = require('fs')
const path = require('path')
const fileName = path.resolve(__dirname, './access_token.json')
console.log('fileName', fileName)
const axios = require('axios')
const APPID = 'wx16f10f1373c8327f'
const APPSECRET = 'c0b4a6ff36face447126fc99b6842d03'
const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`
const updateAccessToken = async () => {
    const result = await axios.get(URL)

    // 写文件
    if (result.data.access_token) {
        fs.writeFileSync(fileName, JSON.stringify({
            access_token: result.data.access_token,
            createtime: new Date()
        }))
    } else {
        // 更新access_token
        await updateAccessToken()
    }
}

const getAccessToken = async () => {
    // 读取文件
    try {
        const readRes = fs.readFileSync(fileName, 'utf-8')
        const readObj = JSON.parse(readRes)
        const createTime = new Date(readObj.createTime).getTime()
        const nowTime = new Date().getTime()
        if ((nowTime - createTime) / 1000 / 60 / 60 >= 2) {
            await updateAccessToken()
            await getAccessToken()
        }
        return readObj.access_token
    } catch (error) {
        await updateAccessToken()
        await getAccessToken()
    }
}

setInterval(async () => {
    await updateAccessToken()
}, 5 * 1000)


module.exports = {
    updateAccessToken,
    getAccessToken
}
// updateAccessToken()

// console.log(getAccessToken())